import { material, project } from '@alilc/lowcode-engine';
import { filterPackages } from '@alilc/lowcode-plugin-inject';
import { Message, Dialog } from '@alifd/next';
import { IPublicTypeProjectSchema, IPublicEnumTransformStage } from '@alilc/lowcode-types';
import schema from './schema.json';
import NetWorkReq from 'src/api';
import { getUrlParams } from 'src/utils/index';
import type { IObject } from 'src/utils/interface';

const generateProjectSchema = (pageSchema: any, i18nSchema: any): IPublicTypeProjectSchema => {
  return {
    componentsTree: [pageSchema],
    componentsMap: material.componentsMap as any,
    version: '1.0.0',
    i18n: i18nSchema,
  };
};

export const saveSchema = async (scenarioName: string = 'unknown') => {
  setProjectSchemaToLocalStorage(scenarioName);
  await setPackagesToLocalStorage(scenarioName);
  Message.success('成功保存到本地');
};

export const resetSchema = async (scenarioName: string = 'unknown') => {
  try {
    await new Promise<void>((resolve, reject) => {
      Dialog.confirm({
        content: '确定要重置吗？您所有的修改都将消失！',
        onOk: () => {
          resolve();
        },
        onCancel: () => {
          reject();
        },
      });
    });
  } catch (err) {
    return;
  }

  let defaultSchema = schema || {
    componentsTree: [{ componentName: 'Page', fileName: 'sample' }],
    componentsMap: material.componentsMap,
    version: '1.0.0',
    i18n: {},
  };

  project.getCurrentDocument()?.importSchema(defaultSchema as any);
  project.simulatorHost?.rerender();

  setProjectSchemaToLocalStorage(scenarioName);
  await setPackagesToLocalStorage(scenarioName);
  Message.success('成功重置页面');
};

const getLSName = (scenarioName: string, ns: string = 'projectSchema') => `${scenarioName}:${ns}`;

export const getProjectSchemaFromLocalStorage = (scenarioName: string) => {
  const { corpId, scenarioName: scenarioName2 } = getUrlParams();
  // console.log(scenarioName, scenarioName2, 'scenarioName2-----');
  if (!scenarioName) {
    scenarioName = scenarioName2;
  }
  return NetWorkReq('getOrgFormSchema', {
    corpId: corpId || 'ding123',
    scenarioName: scenarioName,
    justSchema: 'true',
  })
    .then((res) => {
      console.log(
        'getProjectSchemaFromLocalStorage,scenarioName:' + scenarioName + ',schema:' + res,
      );
      return res;
    })
    .catch((error) => {
      return undefined;
    });
  // window.orgFormSchemaIp +
};

// 设置存储
const setProjectSchemaToLocalStorage = (scenarioName: string) => {
  if (!scenarioName) {
    console.error('scenarioName is required!');
    return;
  }
  const exportSchemaJson = JSON.stringify(project.exportSchema(IPublicEnumTransformStage.Save));
  // if (location.href.includes('localhost:5556')) {
  //   window.localStorage.setItem(getLSName(scenarioName), exportSchemaJson);
  //   return;
  // }
  const urlParams = new URLSearchParams(window.location.search);
  const corpId2 = urlParams.get('corpId');
  const scenarioName2 = urlParams.get('scenarioName');
  if (scenarioName2) {
    scenarioName = scenarioName2;
  }
  console.log(scenarioName, 'objbobjbojbj');
  NetWorkReq('setOrgFormSchema', {
    corpId: corpId2 || 'ding123',
    scenarioName: scenarioName,
    schemaJson: exportSchemaJson,
  })
    .then((res) => {
      console.log('saveSchema success', res);
    })
    .catch((err) => {
      console.error('saveSchema error', err);
    });
  // return;
  // window.orgFormSchemaIp +
  // axios
  //   .post(
  //     '/palm/orgFormSchema/save.json',
  //     new URLSearchParams({
  //       corpId: corpId2 || 'ding123',
  //       scenarioName: scenarioName,
  //       schemaJson: exportSchemaJson,
  //     }),
  //   )
  //   .then((res) => {
  //     console.log('saveSchema success', res);
  //   })
  //   .catch((err) => {
  //     console.error('saveSchema error', err);
  //   });
  // window.localStorage.setItem(
  //   getLSName(scenarioName),
  //   JSON.stringify(project.exportSchema(IPublicEnumTransformStage.Save)),
  // );
};

const setPackagesToLocalStorage = async (scenarioName: string) => {
  if (!scenarioName) {
    console.error('scenarioName is required!');
    return;
  }
  const urlParams = new URLSearchParams(window.location.search);
  const scenarioName2 = urlParams.get('scenarioName');
  const corpId = urlParams.get('corpId');
  if (scenarioName2) {
    scenarioName = scenarioName2;
  }
  const packages = await filterPackages(material.getAssets().packages);
  const params: IObject = {
    corpId,
    scenarioName,
    packageJson: JSON.stringify(packages),
  };
  NetWorkReq('savePackage', params).then((res) => {
    console.log(res, 'res----', params);
  });
  window.localStorage.setItem(getLSName(scenarioName, 'packages'), JSON.stringify(packages));
};

export const getPackagesFromLocalStorage = (scenarioName: string) => {
  const urlParams = new URLSearchParams(window.location.search);
  const corpId = urlParams.get('corpId');
  if (!scenarioName) {
    console.error('scenarioName is required!');
    const scenarioName2 = urlParams.get('scenarioName');
    if (scenarioName2) {
      scenarioName = scenarioName2;
    }
    return;
  }
  return NetWorkReq('getPackage', { corpId, scenarioName }).then((res) => {
    console.log(res, 'res----');
    return res;
  });
  return JSON.parse(window.localStorage.getItem(getLSName(scenarioName, 'packages')) || '{}');
};

export const getPageSchema = async (scenarioName: string = '') => {
  const schemaJson = await getProjectSchemaFromLocalStorage(scenarioName);
  const pageSchema = schemaJson?.componentsTree?.[0];
  if (pageSchema) {
    return pageSchema;
  }
  return null;
};
